import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'

// 是否显示重新登录
let isRelogin = false;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 30000
})
// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof(value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            if (value[key] !== null && typeof (value[key]) !== 'undefined') {
              let params = propName + '[' + key + ']';
              let subPart = encodeURIComponent(params) + '=';
              url += subPart + encodeURIComponent(value[key]) + '&';
            }
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    let code = 200;
    let msg = errorCode['default'];

    if (res && res.data) {
        code = res.data.code || 200;
        msg = errorCode[code] || res.data.msg || errorCode['default'];

        // 检查 msg 是否包含并去除 'exports.default'
        if (typeof msg === 'string' && msg.endsWith('exports.default')) {
            msg = msg.replace(/exports\.default$/, '').trim();
        }
    }

    // Defensive check: Ensure msg is a string and not empty.
    if (typeof msg !== 'string' || msg.trim() === '') {
        console.warn('Notification message is empty or not a string, defaulting to generic error.', msg);
        msg = '请求处理异常，请稍后重试。'; // Fallback to a non-empty generic message
    }

    if (code === 401) {
      if (!isRelogin) {
        isRelogin = true;
        MessageBox.confirm('执行该操作请先登录~', '提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          isRelogin = false;
          store.dispatch('LogOut').then(() => {
            location.href = '/cmsLogin';
          })
        }).catch(() => {
          isRelogin = false;
        });
      }
      return Promise.reject({ code: code, msg: msg, type: 'Authentication_Error' })
    } else if (code === 500) {
      console.error('后端服务错误:', msg);
      return Promise.reject({ code: code, msg: msg, type: 'Backend_Error' })
    } else if (code !== 200) {
      // console.error('API请求错误:', msg); // Removed to diagnose Index: 0, Size: 0 error
      return Promise.reject({ code: code, msg: msg, type: 'API_Request_Error' })
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    console.error('请求失败:', message);
    return Promise.reject({ code: error.response ? error.response.status : null, msg: message, type: 'Request_Failed' })
  }
)

export default service
